package com.hqyj.servletdemo.servlet;

import com.hqyj.servletdemo.service.UsersService;
import com.hqyj.servletdemo.service.impl.UsersServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet(name = "UsersServlet", value = "/users")
public class UsersServlet extends HttpServlet {

    private UsersService usersService = new UsersServiceImpl();
    private String action = "";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.action = request.getParameter("action");
        switch (this.action){
            case "login":
                login(request,response);
                break;
        }
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        String identify = request.getParameter("identify");
        String password = request.getParameter("password");
        System.out.println("用户标识符：" + identify + ",密码：" + password);
        String sessionId = request.getSession(true).getId();
        System.out.println("当前会话ID是：" + sessionId);
        if (usersService.login(identify, password)) {
            System.out.println("UsersServlet==>login()==>登录成功！");
            Cookie cookie = new Cookie("mytoken", sessionId);
            //cookie.setDomain("localhost:8080/servletdemo");
            cookie.setPath("/");
            cookie.setMaxAge(100*24*60*60); //设置有效期为100天
            cookie.setHttpOnly(true);
            response.addCookie(cookie);

            response.sendRedirect("admin");
        }else{
            System.out.println("UsersServlet==>login()==>登录失败！");
            String msg = "登录失败，请检查用户名或者密码是否正确！";
            //String msg = new String("登录失败，请检查用户名或者密码是否正确！");
            System.out.println("转发之前===》"+msg);
            //String msg = new String("login failure!".getBytes(StandardCharsets.UTF_8));

            request.getRequestDispatcher("login.jsp?msg="+msg).forward(request,response);
        }
    }
}
